package models

import (
	"fmt"
	"3rd/errors"
	"3rd/utils/mail"
	"3rd/utils/sms"
	"github.com/astaxie/beego/validation"
)

const (
	Mail = iota
	Mobile
	Unknown
)

var (
	host   = "smtp.163.com"
	port   = 25
	user   = "songkemail@163.com"
	pwd    = "songke198916"
	suject = "验证码"
//【蓝视科技】您的手机验证码：1234，有效时间2分钟。感谢您使用水来了，如有疑问或非本人操作请咨询0371-55355790。
	template = "【蓝视科技】你好，你的验证码是：%s"
	url      = "http://183.57.76.50:8080/sms/sendsms"
	smsusr   = "yanzmfx"
	smspwd   = "yanzmfx"
)

type Media struct {
	mediaType int
	Media     string `json:"media"`
}

func (this *Media) SendCaptcha(len, expire int) error {
	captcha, err := NewCaptcha(len, expire).GenCaptcha(this.Media)
	if err != nil {
		return err
	}
	switch this.ResolveMediaType() {
	case Mail:
		// TODO:
		go mail.SendEmail(host, port, user, pwd, []string{this.Media}, suject, captcha)
		return nil
	case Mobile:
		// TODO:
		sms.InitSendMsg(url, smsusr, smspwd)
		Log.Debug("send msg: " + template, captcha)
		go func() {
			if err := sms.SendMsg(this.Media, fmt.Sprintf(template, captcha)); err != nil {
				Log.Error("send msg %v %v failed:%v", template, captcha, err)
			}
		}()
		return nil
	case Unknown:
		return errors.New(UnknownMedia, "Unknown media type")
	}
	return nil
}

func (this *Media) Valid(v *validation.Validation) {
	if this.ResolveMediaType() == Unknown {
		v.SetError("media", "Unknown media type")
	}
}

func (this *Media) ResolveMediaType() int {
	valid := validation.Validation{}

	if valid.Email(this.Media, "email").Ok {
		this.mediaType = Mail
	} else if valid.Mobile(this.Media, "mobile").Ok {
		this.mediaType = Mobile
	} else {
		this.mediaType = Unknown
	}
	return this.mediaType
}
